/**
 * 园区分布地图
 */

function MapPark(container, settings){
	var defaultOptions = {
			path: '',
			type:null,
			parkid:null,
			size: 200,
			center: "河北",//{lng:lng, lat:lat}
			zoom: 12,
			boundary: null,//边界名（省、市或县的名称）
			getInfoWindow: null,//getInfoWindow(markerVo, callback(title, content))
			onMapStatus: null//地图状态
		};
	var g = this, p = jQuery.extend({}, defaultOptions, settings);;
	g._marks = new JSHashtable();
	g._datas = new JSHashtable();
	
	g._init = function(){
		g.markerNums = 0;
		g._initLoaded = false;
		
		g.map = new qq.maps.Map(container, {
	        center: new qq.maps.LatLng(p.center.lat, p.center.lng),
	        zoom: (p.zoom || 12),
	        mapTypeId: qq.maps.MapTypeId.ROADMAP,
	        zoomControlOptions: {
	            style: qq.maps.ZoomControlStyle.SMALL
	        }
	    });
		g.map.panTo(new qq.maps.LatLng(p.center.lat, p.center.lng));
		
		qq.maps.event.addListener(g.map, 'bounds_changed', function(){
			g._load();
		});
		
		g._infoWindow = new qq.maps.InfoWindow({map: g.map});
		
		g._load();
	};
	
	g.setParkid = function(parkid){
		p.parkid = parkid;
	};
	
	g.centerAndZoom = function(center, zoom){
		g._initLoaded = false;
		g.map.panTo(new qq.maps.LatLng(center.lat, center.lng));
		g.map.zoomTo(parseInt(zoom)||12);
	};
	
	g._mapStatus = function(message){
		if(p.onMapStatus){
			var latLng = g.map.getCenter();
			center = {lat: latLng.getLat(), lng: latLng.getLng()};
			var status = {center: center, zoom: g.map.getZoom(), markerNums: g.markerNums};
			var bounds = g.map.getBounds();
			if(bounds){
				var northEast = bounds.getNorthEast(), southWest = bounds.getSouthWest();
				if(northEast && southWest){
					status.bounds = {E: northEast.getLng(), S: southWest.getLat(), W: southWest.getLng(), N: northEast.getLat()};
				}
			}
			if(message){
				status.message = message;
			}
			p.onMapStatus.call(g, status);
		}
	};
	
	//获取标注图标
	g._getMarkerIcon = function(type, mini){
		return null;
	};
	
	g._load = function(){
		var center = g.map.getCenter(), zoom = g.map.getZoom();
		g._mapStatus();
		
		if(g._locked){
			return;
		}
		g._locked = true;
		g._token = '1'+String(Math.random()).substr(2);
		
		//地图边界
		var bounds = g.map.getBounds();
		if(!bounds){
			g._locked = false;
			return;
		}
		var northEast = bounds.getNorthEast(), southWest = bounds.getSouthWest();
		if(!northEast){
			g._locked = false;
			return;
		}
		
		var param = [];
		param.push('token='+g._token);
		param.push('wlng='+southWest.getLng());
		param.push('elng='+northEast.getLng());
		param.push('nlat='+northEast.getLat());
		param.push('slat='+southWest.getLat());
		param.push('zoom='+zoom);
		param.push('size='+(p.size || 200));
		param.push('markerid='+(!p.marker ? '' : (p.marker.id || '')));
		param.push('type='+(p.type || ''));
		param.push('parkid='+(p.parkid || ''));
		
		jQuery.ajax({
			url:  p.path + '/parkmap/loadMapMarkers.json?'+ param.join("&"),
			type: 'GET',
			cache: false,
			dataType: 'json',
			success: function(data){
				if(typeof(data)=='string'){
					data = jQuery.parseJSON(data);
	    		}
				var token = data.token;
				if(token!=g._token){
					g._locked = false;
					return;
				}
				var list = data.list;//标注点列表
				if(list!=null && list.length>0){
					g.markerNums = list.length;
					var listMap = {};
					for(var i=0, len=list.length; i<len; i++){
						var mkrVo = list[i];
						listMap[mkrVo.id] = mkrVo;
					}
					//删除不显示的现有标注
					var keys = g._marks.getKeys();
					for(var i=0, len=keys.length; i<len; i++){
						var k=keys[i];
						if(typeof(listMap[k])=="undefined"||listMap[k]==null){
							g._deleteMarker(k);
						}
					}
					delete listMap;
					delete keys;
					//将新标注添加到地图
					for(var i=0, len=list.length; i<len; i++){
						var mkrVo = list[i];
						if(!g._marks.containsKey(mkrVo.id)){//如果地图上没有则添加
							var opt = {position: new qq.maps.LatLng(mkrVo.lat, mkrVo.lng), map: g.map}, icon = g._getMarkerIcon(mkrVo.type);
							if(icon){
								opt.icon = icon;
							}
							var marker = new qq.maps.Marker(opt);
							marker.mid = mkrVo.id;
							mkrVo._listener = qq.maps.event.addListener(marker, 'click', g._openInfoWindow);
							marker.setTitle(mkrVo.name);
							g._marks.put(mkrVo.id, marker);
							g._datas.put(mkrVo.id, mkrVo);
						}
					}
				}else{
					g.markerNums = 0;
					g._deleteAll();
				}
				g._locked = false;
				g._mapStatus();
				
				if(!g._initLoaded){
					g._initLoaded = true;
					g.showInfoWindow(p.parkid);
				}
			},
			error:function(p1,p2,p3){
				g._locked = false;
				g._mapStatus('发生AJAX错误！'+p1+p2+p3);
			}
		});
		
	};
	
	//删除所有标注
	g._deleteAll=function(){
		var keys = g._marks.getKeys();
		for(var i=0, len=keys.length; i<len; i++){
			g._deleteMarker(keys[i]);
		}
	};
	
	//删除标注
	g._deleteMarker=function(mid){
		var marker = g._marks.get(mid);
		if(!marker){
			g._marks.remove(mid);
			g._datas.remove(mid);
			return;
		}
		var iw = g._infoWindow;
		if(iw.mkrid == marker.mid){
			g._infoWindow.setMap(null);
		}
		var mkrVo = g._datas.get(mid);
		if(mkrVo){
			qq.maps.event.removeListener(mkrVo._listener);
		}
		marker.setMap(null);
		g._marks.remove(mid);
		g._datas.remove(mid);
	};
	
	//关闭信息窗口
	g.closeInfoWindow=function(){
		if(g._infoWindow){
			g._infoWindow.setMap(null);
		}
	};
	
	//打开指定标注的信息窗口
	g.showInfoWindow=function(mid){
		var marker = g._marks.get(mid);
		if(marker){
			g._openInfoWindow(marker);
		}else{
			g.closeInfoWindow();
		}
	};
	
	//打开信息窗口
	g._openInfoWindow=function(evt){
		var marker = (evt instanceof qq.maps.Marker) ? evt : evt.target;
		if(g._infoWindow){
			var iw = g._infoWindow;
			iw.setMap(null);
			iw.mkrid = marker.mid;
			var mkrVo = g._datas.get(marker.mid);
			if(typeof(p.getInfoWindow)=='function'){
				p.getInfoWindow.call(g, mkrVo, function(title, content){
					if(content && content.indexOf('<') == -1){
						content = g.farmatContent(content);
					}
					if(title){
						content = '<span class="mkr_title">'+title+'</span>'+content;
					}
					iw.setContent(content || '');
					iw.setMap(g.map);
					iw.setPosition(marker);
					iw.open();
				});
			}else{
				var content = mkrVo.remark;
				if(content && content.indexOf('<') == -1){
					content = g.farmatContent(content);
				}
				content = '<span class="mkr_title">'+mkrVo.name+'</span>'+content;
				iw.setContent(content || '');
				iw.setMap(g.map);
				iw.setPosition(marker);
				iw.open();
			}
		}
	};
	
	//将内容用段落标签进行格式化
	g.farmatContent=function(content){
		if(content){
			content = content.replace(/&|>|<|"/g, function(){
				var c = arguments[0];
				switch(c){
				case '&': return '&amp;';
				case '>': return '&gt;';
				case '<': return '&lt;';
				case '"': return '&quot;';
				}
			});
			content = content.replace(/\r\n|\r|\n/g, '</p><p class="mkr_content">');
			content = '<p class="mkr_content">' + content +"</p>";
			content = content.replace('<p class="mkr_content"></p>', '');
		}
		return content;
	};
	
	g._init();
}

